package chan.project.smartlawlawyer.controller;

import chan.project.smartlawcommon.annotation.AuthCheck;
import chan.project.smartlawcommon.common.BaseResponse;
import chan.project.smartlawcommon.common.DeleteRequest;
import chan.project.smartlawcommon.common.ErrorCode;
import chan.project.smartlawcommon.common.ResultUtils;
import chan.project.smartlawcommon.constant.UserConstant;
import chan.project.smartlawcommon.exception.BusinessException;
import chan.project.smartlawcommon.exception.ThrowUtils;
import chan.project.smartlawlawyer.service.LawyerInfoService;
import chan.project.smartlawmodel.dto.lawyer.LawyerInfoAddRequest;
import chan.project.smartlawmodel.dto.lawyer.LawyerInfoEditRequest;
import chan.project.smartlawmodel.dto.lawyer.LawyerInfoQueryRequest;
import chan.project.smartlawmodel.dto.lawyer.LawyerInfoUpdateRequest;
import chan.project.smartlawmodel.entity.LawyerInfo;
import chan.project.smartlawmodel.entity.UserInfo;
import chan.project.smartlawmodel.vo.LawyerInfoVO;
import chan.project.smartlawmodel.vo.UserInfoVO;
import chan.project.smartlawservice.userService.UserFeignClient;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * 律师接口
 *
 * @author <a href="https://github.com/kavansp">kavansp</a>
 * @from <a href="https://www.code-nav.cn">编程导航学习圈</a>
 */
@RestController
@RequestMapping("/lawyer")
@Slf4j
public class LawyerInfoController {

    @Resource
    private LawyerInfoService lawyerInfoService;

    @Resource
    private UserFeignClient userService;

    // region 增删改查

    /**
     * 创建律师
     *
     * @param lawyerInfoAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addLawyerInfo(@RequestBody LawyerInfoAddRequest lawyerInfoAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(lawyerInfoAddRequest == null, ErrorCode.PARAMS_ERROR);

        LawyerInfo lawyerInfo = new LawyerInfo();
        BeanUtils.copyProperties(lawyerInfoAddRequest, lawyerInfo);
        // 数据校验
        lawyerInfoService.validLawyerInfo(lawyerInfo, true);
        UserInfoVO loginUser = userService.getLoginUser();
        lawyerInfo.setUserId(loginUser.getId());
        // 写入数据库
        boolean result = lawyerInfoService.save(lawyerInfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newLawyerInfoId = lawyerInfo.getId();
        return ResultUtils.success(newLawyerInfoId);
    }

    /**
     * 删除律师
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteLawyerInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserInfoVO user = userService.getLoginUser();
        long id = deleteRequest.getId();
        // 判断是否存在
        LawyerInfo oldLawyerInfo = lawyerInfoService.getById(id);
        ThrowUtils.throwIf(oldLawyerInfo == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = lawyerInfoService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新律师（仅管理员可用）
     *
     * @param lawyerInfoUpdateRequest
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateLawyerInfo(@RequestBody LawyerInfoUpdateRequest lawyerInfoUpdateRequest) {
        if (lawyerInfoUpdateRequest == null || lawyerInfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //在此处将实体类和 DTO 进行转换
        LawyerInfo lawyerInfo = new LawyerInfo();
        BeanUtils.copyProperties(lawyerInfoUpdateRequest, lawyerInfo);
        // 数据校验
        lawyerInfoService.validLawyerInfo(lawyerInfo, false);
        // 判断是否存在
        long id = lawyerInfoUpdateRequest.getId();
        LawyerInfo oldLawyerInfo = lawyerInfoService.getById(id);
        ThrowUtils.throwIf(oldLawyerInfo == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = lawyerInfoService.updateById(lawyerInfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取律师（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<LawyerInfoVO> getLawyerInfoVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        LawyerInfo lawyerInfo = lawyerInfoService.getById(id);
        ThrowUtils.throwIf(lawyerInfo == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(lawyerInfoService.getLawyerInfoVO(lawyerInfo, request));
    }

    /**
     * 分页获取律师列表（仅管理员可用）
     *
     * @param lawyerInfoQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<LawyerInfo>> listLawyerInfoByPage(@RequestBody LawyerInfoQueryRequest lawyerInfoQueryRequest) {
        long current = lawyerInfoQueryRequest.getCurrent();
        long size = lawyerInfoQueryRequest.getPageSize();
        // 查询数据库
        Page<LawyerInfo> lawyerInfoPage = lawyerInfoService.page(new Page<>(current, size),
                lawyerInfoService.getQueryWrapper(lawyerInfoQueryRequest));
        return ResultUtils.success(lawyerInfoPage);
    }

    /**
     * 分页获取律师列表（封装类）
     *
     * @param lawyerInfoQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<LawyerInfoVO>> listLawyerInfoVOByPage(@RequestBody LawyerInfoQueryRequest lawyerInfoQueryRequest,
                                                               HttpServletRequest request) {
        long current = lawyerInfoQueryRequest.getCurrent();
        long size = lawyerInfoQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<LawyerInfo> lawyerInfoPage = lawyerInfoService.page(new Page<>(current, size),
                lawyerInfoService.getQueryWrapper(lawyerInfoQueryRequest));
        // 获取封装类
        return ResultUtils.success(lawyerInfoService.getLawyerInfoVOPage(lawyerInfoPage, request));
    }

    /**
     * 分页获取当前登录用户创建的律师列表
     *
     * @param lawyerInfoQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<LawyerInfoVO>> listMyLawyerInfoVOByPage(@RequestBody LawyerInfoQueryRequest lawyerInfoQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(lawyerInfoQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        UserInfoVO loginUser = userService.getLoginUser();
        lawyerInfoQueryRequest.setUserId(loginUser.getId());
        long current = lawyerInfoQueryRequest.getCurrent();
        long size = lawyerInfoQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<LawyerInfo> lawyerInfoPage = lawyerInfoService.page(new Page<>(current, size),
                lawyerInfoService.getQueryWrapper(lawyerInfoQueryRequest));
        // 获取封装类
        return ResultUtils.success(lawyerInfoService.getLawyerInfoVOPage(lawyerInfoPage, request));
    }

    /**
     * 编辑律师（给用户使用）
     *
     * @param lawyerInfoEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editLawyerInfo(@RequestBody LawyerInfoEditRequest lawyerInfoEditRequest, HttpServletRequest request) {
        if (lawyerInfoEditRequest == null || lawyerInfoEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        LawyerInfo lawyerInfo = new LawyerInfo();
        BeanUtils.copyProperties(lawyerInfoEditRequest, lawyerInfo);
        // 数据校验
        lawyerInfoService.validLawyerInfo(lawyerInfo, false);
        UserInfoVO loginUser = userService.getLoginUser();
        // 判断是否存在
        long id = lawyerInfoEditRequest.getId();
        LawyerInfo oldLawyerInfo = lawyerInfoService.getById(id);
        ThrowUtils.throwIf(oldLawyerInfo == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldLawyerInfo.getUserId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = lawyerInfoService.updateById(lawyerInfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

}
